﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Web.Mvc;
using Sharp.DataTransferObject;
using Sharp.Infrastructure.WebApiClient;
using Sharp.Portal.Mvc;
using Sharp.ServiceContracts;
using Sharp.WebBooter;

using System.Threading.Tasks;
using Sharp.Infrastructure;
using Sharp.Infrastructure.Search;
using Sharp.Portal.Mvc.Models;
using Sharp.WebBooter.Areas.Platform.Models;
using System.Linq;
// ReSharper disable Mvc.ViewNotResolved

namespace Sharp.WebBooter.Areas.Platform.Controllers
{
    [Authorize]
    [AutomaticTemplate]
    public class GroupController : SharpController
    {
        // GET: Manage/Group
        public ActionResult Index(string containerId)
        {
            return View(new GroupIndexModel());
        }
        /// <summary>
        ///     分页数据
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public ActionResult GetPaged(DataTableParameter parameters)
        {
            using (var proxy = new WebApiClientServiceProxy<IEnterpriseService>())
            {
                var pageInfo = proxy.Channel.GetGroupPaged(parameters.ToPagingFeature());

                return this.Store(pageInfo);
            }
        }
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            GroupDTO dto = null;
            using (var proxy = new WebApiClientServiceProxy<IEnterpriseService>())
            {
                dto = proxy.Channel.GetGroupInfo(id.Value);
            }
            if (dto == null)
            {
                return HttpNotFound();
            }

            var viewModel = dto.To<GroupModel>();
            viewModel.OrgIdDataSource = new zTreeNode();

            return View("Edit", viewModel);
        }

        public async Task<ActionResult> Create()
        {
            var vm = new GroupModel();
            IEnumerable<OrgDTO> allOrgs;
            using (var proxy = new WebApiClientServiceProxy<IEnterpriseService>())
            {
                allOrgs = await proxy.Channel.GetOrgs();
            }
            vm.OrgIdDataSource = new zTreeNode();
            OrgController.Build(allOrgs, vm.OrgIdDataSource, null);
            return View(vm);
        }


        public async Task<ActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            GroupDTO dto;
            IEnumerable<OrgDTO> allOrgs;
            using (var proxy = new WebApiClientServiceProxy<IEnterpriseService>())
            {
                dto = proxy.Channel.GetGroupInfo(id.Value);
                allOrgs = await proxy.Channel.GetOrgs();
            }
            if (dto == null)
            {
                return HttpNotFound();
            }

            var vm = dto.To<GroupModel>();
            vm.OrgIdDataSource = new zTreeNode();
            OrgController.Build(allOrgs, vm.OrgIdDataSource, null);

            return View(vm);
        }


        public ActionResult Save(GroupModel group)
        {
            Result res;
            using (var proxy = new WebApiClientServiceProxy<IEnterpriseService>())
            {
                var dto = group.To<GroupDTO>();

                res = proxy.Channel.SaveGroup(dto);
            }

            return this.JsonNet(res);
        }


        public ActionResult Delete(int[] ids)
        {
            Result res;
            using (var proxy = new WebApiClientServiceProxy<IEnterpriseService>())
            {
                res = proxy.Channel.DeleteGroups(ids);
            }

            return this.JsonNet(res);
        }

        public ActionResult UserDialog(int? groupId)
        {
            return View("UserDialog", groupId);
        }

        /// <summary>
        /// 关联用户
        /// </summary>
        /// <param name="groupId"></param>
        /// <param name="userIds">用户Id</param>
        /// <returns></returns>
        [Permission("分配角色", 3, "001003004")]
        public ActionResult Relation(int groupId, int[] userIds)
        {
            using (var proxy = new WebApiClientServiceProxy<IUserService>())
            {
                var res = proxy.Channel.RelationUserForGroup(groupId, userIds);

                return this.JsonNet(res);
            }
        }


        /// <summary>
        ///     弹出框的数据源
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public ActionResult GetUserPaged(DataTableParameter parameters, int? groupId)
        {
            PagedResult<UserDTO> page;
            using (var proxy = new WebApiClientServiceProxy<IUserService>())
            {
                page = proxy.Channel.GetUsersPaged(parameters.ToPagingFeature());

            }
            if (groupId.HasValue)
            {
                using (var proxy = new WebApiClientServiceProxy<IEnterpriseService>())
                {
                    var group = proxy.Channel.GetGroupInfo(groupId.Value);

                    foreach(var u in page.Data)
                    {
                        u.Selected = group.Users.Any(r => r.Id == u.Id);
                    }
                }
            }

            return this.Store(page);
        }
        public ActionResult LoadWindowForUser(int groupId)
        {
            ViewBag.Title = "选取用户";
            ViewBag.groupId = groupId;
            ViewBag.DataUrl = Url.Action("GetUserPaged", new { groupId = groupId });
            ViewBag.PostUrl = Url.Action("Relation");
            ViewBag.Save = "new Group().relation(event,'"+ groupId + "')";
            return View("../User/WindowForUser");
        }
    }
}
